package com.zhz.leetcode;

import java.util.Arrays;

/**
 * 283、移动零
 * https://leetcode-cn.com/problems/move-zeroes/
 */
public class MoveZeroes283 {

    public static void main(String[] args) {

        MoveZeroes283 movingZero = new MoveZeroes283();
        // nums = [0,1,0,3,12] 输出：[1,3,12,0,0]
        int[] nums = {1};
        movingZero.moveZeroes1(nums);
        System.out.println(Arrays.toString(nums));
    }

    /**
     * 比如说：[0, 1, 0, 3, 12]
     * 第一次: i = 0 时,nums[0]=0,因此跳过。
     * 第二次: i = 1 时,nums[i]=1 因此进入判断，此时index=0，将nums[i]赋值给nums[index],并且index != 1，因此nums[1]=0 此时数组为[1,0,0,3,12]
     * 以此类推...
     */
    private void moveZeroes(int[] nums) {
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[index] = nums[i];
                if (index != i) {
                    nums[i] = 0;
                }
                index++;
            }
        }
        System.out.println(Arrays.toString(nums));
    }


    /**
     * 使用双指针来解题
     */
    private void moveZeroes1(int[] nums) {
        int slow = 0, fast = 0;
        while (fast < nums.length) {
            if (nums[fast] != 0) {
                nums[slow] = nums[fast];
                if (slow != fast) nums[fast] = 0;
                slow += 1;
            }
            fast += 1;
        }
    }
}
